// ==UserScript==
// @name         禅道Bug剩余天数提醒
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  在禅道Bug列表中添加剩余天数列，根据级别自动计算截止日期，临近超期标红
// @author       You
// @match        https://www.j-do.cn:9012/zentao/bug-browse-*
// @match        https://www.j-do.cn:9012/zentao/bug-*
// @match        https://www.j-do.cn:9012/zentao/user-login*
// @icon         https://www.zentao.net/favicon.ico
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 配置：根据级别设置截止天数
    const DEADLINE_CONFIG = {
        '1': 7,   // 严重：7天
        '2': 14,  // 中等：14天
        '3': 30,  // 轻微：30天
        '4': -1   // 建议：不限
    };

    // 配置：剩余天数预警阈值
    const WARNING_DAYS = {
        '1': 2,   // 严重：剩余2天内标红
        '2': 3,   // 中等：剩余3天内标红
        '3': 7,   // 轻微：剩余7天内标红
        '4': -1   // 建议：不标红
    };

    /**
     * 解析日期字符串（如 "10-16 11:40" 或 "10-16"）
     */
    function parseZentaoDate(dateStr) {
        if (!dateStr) return null;

        const now = new Date();
        const currentYear = now.getFullYear();

        // 解析 "月-日" 或 "月-日 时:分"
        const parts = dateStr.trim().split(' ');
        const datePart = parts[0]; // "10-16"
        const timePart = parts[1] || '00:00'; // "11:40" 或默认 "00:00"

        const [month, day] = datePart.split('-').map(num => parseInt(num, 10));
        const [hour, minute] = timePart.split(':').map(num => parseInt(num, 10));

        const date = new Date(currentYear, month - 1, day, hour || 0, minute || 0);

        // 如果解析的日期在未来（跨年情况），使用去年
        if (date > now) {
            date.setFullYear(currentYear - 1);
        }

        return date;
    }

    /**
     * 计算两个日期之间的天数差
     */
    function daysBetween(date1, date2) {
        const oneDay = 24 * 60 * 60 * 1000;
        return Math.round((date2 - date1) / oneDay);
    }

    /**
     * 处理Bug表格
     */
    function processBugTable() {
        const table = document.querySelector('#bugList, table.table.has-sort-head');
        if (!table) {
            console.log('[禅道Bug提醒] 未找到Bug表格');
            return;
        }

        const thead = table.querySelector('thead tr');
        const tbody = table.querySelector('tbody');

        if (!thead || !tbody) {
            console.log('[禅道Bug提醒] 表格结构异常');
            return;
        }

        // 检查是否已经添加过
        if (thead.querySelector('.th-deadline')) {
            console.log('[禅道Bug提醒] 已经添加过剩余天数列');
            return;
        }

        // 1. 在表头添加"剩余天数"列
        const deadlineHeader = document.createElement('th');
        deadlineHeader.className = 'c-deadline-header';
        deadlineHeader.setAttribute('data-flex', 'true');
        deadlineHeader.setAttribute('data-width', '90px');
        deadlineHeader.style.width = '90px';
        deadlineHeader.style.minWidth = '90px';
        deadlineHeader.style.maxWidth = '90px';
        deadlineHeader.setAttribute('title', '剩余天数');
        deadlineHeader.innerHTML = '<a href="javascript:;" class="header deadline-sort">剩余天数</a>';

        // 插入到"创建日期"列之后
        const dateHeader = thead.querySelector('.c-openedDate');
        if (dateHeader) {
            dateHeader.after(deadlineHeader);
        } else {
            thead.appendChild(deadlineHeader);
        }

        // 2. 为每一行添加剩余天数单元格
        const rows = tbody.querySelectorAll('tr[data-id]');
        const now = new Date();

        rows.forEach(row => {
            // 获取指派人
            const assignedCell = row.querySelector('.c-assignedTo');
            const assignedText = assignedCell ? assignedCell.textContent.trim() : '';
            
            // 检查是否指派给测试人员（已解决，进入测试阶段）
            const isInTesting = assignedText.includes('乔梦威') || assignedText.includes('杨文俊');
            if (isInTesting) {
                row.classList.add('bug-in-testing');
                row.setAttribute('title', '已指派给测试，等待验证');
            }

            // 获取严重程度
            const severityCell = row.querySelector('.c-severity span');
            const severity = severityCell ? severityCell.getAttribute('data-severity') || severityCell.getAttribute('title') : '4';

            // 获取创建日期
            const dateCell = row.querySelector('.c-openedDate');
            const dateText = dateCell ? dateCell.textContent.trim() : '';

            // 创建剩余天数单元格
            const deadlineCell = document.createElement('td');
            deadlineCell.className = 'c-deadline';
            deadlineCell.style.width = '90px';
            deadlineCell.style.minWidth = '90px';
            deadlineCell.style.maxWidth = '90px';

            if (!dateText || severity === '4') {
                // 级别4或无日期，显示"不限"
                deadlineCell.innerHTML = '<span class="text-muted">不限</span>';
                deadlineCell.setAttribute('data-days', '99999');
            } else {
                // 解析创建日期
                const createdDate = parseZentaoDate(dateText);
                if (!createdDate) {
                    deadlineCell.innerHTML = '<span class="text-muted">-</span>';
                    deadlineCell.setAttribute('data-days', '99999');
                } else {
                    // 计算截止日期
                    const deadlineDays = DEADLINE_CONFIG[severity] || 30;
                    const deadlineDate = new Date(createdDate);
                    deadlineDate.setDate(deadlineDate.getDate() + deadlineDays);

                    // 计算剩余天数
                    const remainingDays = daysBetween(now, deadlineDate);
                    deadlineCell.setAttribute('data-days', remainingDays);

                    // 确定显示样式
                    const warningThreshold = WARNING_DAYS[severity] || 3;
                    let displayClass = '';
                    let displayText = '';

                    if (remainingDays < 0) {
                        // 已超期
                        displayClass = 'text-danger';
                        displayText = `<strong>超期${Math.abs(remainingDays)}天</strong>`;
                    } else if (remainingDays <= warningThreshold) {
                        // 临近超期（标红）
                        displayClass = 'text-danger';
                        displayText = `<strong>剩余${remainingDays}天</strong>`;
                    } else if (remainingDays <= warningThreshold * 2) {
                        // 预警
                        displayClass = 'text-warning';
                        displayText = `剩余${remainingDays}天`;
                    } else {
                        // 正常
                        displayClass = 'text-muted';
                        displayText = `剩余${remainingDays}天`;
                    }

                    deadlineCell.innerHTML = `<span class="${displayClass}" title="创建于${dateText}，${deadlineDays}天内需解决">${displayText}</span>`;
                }
            }

            // 插入单元格
            const dateCell2 = row.querySelector('.c-openedDate');
            if (dateCell2) {
                dateCell2.after(deadlineCell);
            } else {
                row.appendChild(deadlineCell);
            }
        });

        console.log(`[禅道Bug提醒] 成功处理${rows.length}个Bug`);

        // 3. 添加排序功能
        deadlineHeader.querySelector('.deadline-sort').addEventListener('click', function(e) {
            e.preventDefault();
            sortTableByDeadline();
        });
    }

    /**
     * 按剩余天数排序
     */
    function sortTableByDeadline() {
        const tbody = document.querySelector('#bugList tbody, table.table.has-sort-head tbody');
        if (!tbody) return;

        const rows = Array.from(tbody.querySelectorAll('tr[data-id]'));

        // 按剩余天数排序（升序）
        rows.sort((a, b) => {
            const daysA = parseInt(a.querySelector('.c-deadline').getAttribute('data-days') || '99999', 10);
            const daysB = parseInt(b.querySelector('.c-deadline').getAttribute('data-days') || '99999', 10);
            return daysA - daysB;
        });

        // 重新插入排序后的行
        rows.forEach(row => tbody.appendChild(row));

        console.log('[禅道Bug提醒] 已按剩余天数排序');
    }

    /**
     * 添加自定义样式
     */
    function addCustomStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .c-deadline-header,
            .th-deadline,
            .c-deadline {
                text-align: center !important;
                vertical-align: middle !important;
                font-size: 13px;
                width: 90px !important;
                min-width: 90px !important;
                max-width: 90px !important;
                padding: 8px 5px !important;
            }
            .c-deadline .text-danger {
                color: #dc3545 !important;
                font-weight: 600;
            }
            .c-deadline .text-warning {
                color: #ffc107 !important;
                font-weight: 500;
            }
            .c-deadline .text-muted {
                color: #6c757d;
            }
            .deadline-sort {
                cursor: pointer;
                user-select: none;
            }
            .deadline-sort:hover {
                text-decoration: underline;
            }

            /* 测试阶段Bug样式（整行绿色背景） */
            tr.bug-in-testing {
                background: linear-gradient(to right, #e8f5e9 0%, #f1f8f4 50%, transparent 100%) !important;
                box-shadow: inset 4px 0 0 #4caf50 !important;
            }

            tr.bug-in-testing:hover {
                background: linear-gradient(to right, #c8e6c9 0%, #dcedc8 50%, #f5f5f5 100%) !important;
            }

            /* 汇总条样式 - 简洁风格 */
            .zentao-summary-bar {
                background: #f7f8fa;
                border: 1px solid #e5e5e5;
                border-radius: 4px;
                padding: 8px 15px;
                margin-bottom: 15px;
                display: flex;
                align-items: center;
                gap: 0;
                font-size: 13px;
            }

            .summary-item {
                display: flex;
                align-items: center;
                gap: 6px;
                padding: 0 12px;
            }

            .summary-icon {
                font-size: 14px;
            }

            .summary-label {
                color: #666;
                font-size: 12px;
            }

            .summary-value {
                font-weight: 600;
                color: #333;
                font-size: 15px;
                min-width: 20px;
                text-align: center;
            }

            .summary-value.has-value {
                color: #3280fc;
            }

            .summary-value.danger-value {
                color: #dc3545;
            }

            .summary-value.warning-value {
                color: #ff9800;
            }

            .summary-value.success-value {
                color: #28a745;
            }

            .summary-detail {
                font-size: 11px;
                color: #999;
                margin-left: 4px;
            }

            .summary-divider {
                width: 1px;
                height: 20px;
                background: #ddd;
                margin: 0 4px;
            }
        `;
        document.head.appendChild(style);
    }

    /**
     * 创建今日新增汇总面板
     */
    function createTodaySummary() {
        const tbody = document.querySelector('#bugList tbody, table.table.has-sort-head tbody');
        if (!tbody) return;

        const rows = tbody.querySelectorAll('tr[data-id]');
        const today = new Date();
        const todayStr = `${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

        // 统计数据
        let todayTotal = 0;
        let todayLevel1 = 0;
        let todayLevel2 = 0;
        let todayLevel3 = 0;
        let todayLevel4 = 0;
        let urgentBugs = 0;
        let overdueBugs = 0;
        let testingBugs = 0;  // 测试中的Bug

        rows.forEach(row => {
            // 检查是否测试中
            if (row.classList.contains('bug-in-testing')) {
                testingBugs++;
            }

            // 获取创建日期
            const dateCell = row.querySelector('.c-openedDate');
            const dateText = dateCell ? dateCell.textContent.trim() : '';

            // 检查是否今日新增
            if (dateText.startsWith(todayStr)) {
                todayTotal++;

                // 统计级别
                const severityCell = row.querySelector('.c-severity span');
                const severity = severityCell ? severityCell.getAttribute('data-severity') || '4' : '4';

                if (severity === '1') todayLevel1++;
                else if (severity === '2') todayLevel2++;
                else if (severity === '3') todayLevel3++;
                else todayLevel4++;
            }

            // 统计紧急和超期
            const deadlineCell = row.querySelector('.c-deadline');
            if (deadlineCell) {
                const days = parseInt(deadlineCell.getAttribute('data-days') || '99999', 10);
                const span = deadlineCell.querySelector('span');
                if (span && span.classList.contains('text-danger')) {
                    if (days < 0) {
                        overdueBugs++;
                    } else {
                        urgentBugs++;
                    }
                }
            }
        });

        // 创建简洁的汇总条
        const panel = document.createElement('div');
        panel.className = 'zentao-summary-bar';
        panel.innerHTML = `
            <div class="summary-item today-item">
                <span class="summary-icon">📅</span>
                <span class="summary-label">今日新增</span>
                <span class="summary-value ${todayTotal > 0 ? 'has-value' : ''}">${todayTotal}</span>
                ${todayTotal > 0 ? `<span class="summary-detail">(严重${todayLevel1} 中${todayLevel2} 轻${todayLevel3})</span>` : ''}
            </div>
            <div class="summary-divider"></div>
            <div class="summary-item urgent-item">
                <span class="summary-icon">⚠️</span>
                <span class="summary-label">已超期</span>
                <span class="summary-value ${overdueBugs > 0 ? 'danger-value' : ''}">${overdueBugs}</span>
            </div>
            <div class="summary-divider"></div>
            <div class="summary-item warning-item">
                <span class="summary-icon">⏰</span>
                <span class="summary-label">临近超期</span>
                <span class="summary-value ${urgentBugs > 0 ? 'warning-value' : ''}">${urgentBugs}</span>
            </div>
            <div class="summary-divider"></div>
            <div class="summary-item testing-item">
                <span class="summary-icon">✅</span>
                <span class="summary-label">测试中</span>
                <span class="summary-value ${testingBugs > 0 ? 'success-value' : ''}">${testingBugs}</span>
            </div>
            <div class="summary-divider"></div>
            <div class="summary-item total-item">
                <span class="summary-icon">📊</span>
                <span class="summary-label">总计</span>
                <span class="summary-value">${rows.length}</span>
            </div>
        `;

        // 插入到Bug列表上方
        const bugForm = document.querySelector('.main-table.table-bug, #bugForm');
        if (bugForm) {
            bugForm.parentNode.insertBefore(panel, bugForm);
        }

        console.log(`[禅道Bug提醒] 今日新增${todayTotal}个Bug`);
    }

    /**
     * ==================== 登录页面快捷登录功能 ====================
     */
    
    /**
     * 创建快捷登录卡片
     */
    function createQuickLoginCards() {
        // 预设的账号列表（可以添加更多）
        const accounts = [
            { username: 'juzhuohan', password: '111.', name: '鞠卓瀚', role: '研发', color: '#667eea' },
            { username: 'zhuhuiping', password: '111.', name: '朱会平', role: '研发', color: '#764ba2' },
            // 添加更多账号...
        ];

        // 检查localStorage中是否有保存的账号
        const savedAccounts = localStorage.getItem('zentao_quick_accounts');
        if (savedAccounts) {
            try {
                const parsed = JSON.parse(savedAccounts);
                if (Array.isArray(parsed) && parsed.length > 0) {
                    accounts.length = 0;
                    accounts.push(...parsed);
                }
            } catch (e) {
                console.log('[快捷登录] 读取保存账号失败');
            }
        }

        // 创建卡片容器
        const container = document.createElement('div');
        container.className = 'quick-login-container';
        container.innerHTML = `
            <div class="quick-login-header">
                <h3>⚡ 快捷登录</h3>
                <button class="add-account-btn" title="添加账号">+</button>
            </div>
            <div class="quick-login-cards" id="quickLoginCards"></div>
            <div class="quick-login-footer">
                <small>密码加密存储在本地浏览器</small>
            </div>
        `;

        // 渲染账号卡片
        const cardsContainer = container.querySelector('#quickLoginCards');
        accounts.forEach((account, index) => {
            const card = document.createElement('div');
            card.className = 'account-card';
            card.style.borderColor = account.color;
            card.innerHTML = `
                <div class="card-avatar" style="background: ${account.color}">
                    ${account.name.charAt(0)}
                </div>
                <div class="card-info">
                    <div class="card-name">${account.name}</div>
                    <div class="card-role">${account.role}</div>
                    <div class="card-username">${account.username}</div>
                </div>
                <button class="card-login-btn" data-index="${index}">登录</button>
            `;

            // 点击卡片登录
            card.querySelector('.card-login-btn').addEventListener('click', () => {
                quickLogin(account);
            });

            cardsContainer.appendChild(card);
        });

        // 添加账号按钮
        container.querySelector('.add-account-btn').addEventListener('click', () => {
            showAddAccountDialog();
        });

        // 插入到登录面板右侧
        const loginPanel = document.querySelector('#loginPanel, #login');
        if (loginPanel) {
            const parent = loginPanel.parentElement;
            if (parent) {
                parent.style.display = 'flex';
                parent.style.gap = '20px';
                parent.style.alignItems = 'flex-start';
                loginPanel.after(container);
            }
        }
    }

    /**
     * 快捷登录
     */
    function quickLogin(account) {
        const usernameInput = document.querySelector('#account, input[name="account"]');
        const passwordInput = document.querySelector('input[type="password"], input[name="password"]');

        if (!usernameInput || !passwordInput) {
            alert('未找到登录表单');
            return;
        }

        // 填充账号
        usernameInput.value = account.username;

        // 如果有保存密码，填充密码
        if (account.password) {
            passwordInput.value = account.password;
        } else {
            // 没有密码，提示用户输入
            passwordInput.focus();
            passwordInput.placeholder = '请输入密码';
            passwordInput.style.borderColor = '#667eea';
            return;
        }

        // 自动提交登录
        setTimeout(() => {
            const submitBtn = document.querySelector('#submit, button[type="submit"]');
            if (submitBtn) {
                submitBtn.click();
            }
        }, 100);
    }

    /**
     * 显示添加账号对话框
     */
    function showAddAccountDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'add-account-dialog';
        dialog.innerHTML = `
            <div class="dialog-overlay"></div>
            <div class="dialog-content">
                <div class="dialog-header">
                    <h3>添加快捷登录账号</h3>
                    <button class="dialog-close">&times;</button>
                </div>
                <div class="dialog-body">
                    <div class="form-group">
                        <label>姓名</label>
                        <input type="text" id="newAccountName" placeholder="如：张三" />
                    </div>
                    <div class="form-group">
                        <label>角色</label>
                        <input type="text" id="newAccountRole" placeholder="如：研发" />
                    </div>
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" id="newAccountUsername" placeholder="如：zhangsan" />
                    </div>
                    <div class="form-group">
                        <label>密码（可选）</label>
                        <input type="password" id="newAccountPassword" placeholder="留空则每次需手动输入" />
                        <small style="color: #999;">密码会加密保存在本地浏览器</small>
                    </div>
                </div>
                <div class="dialog-footer">
                    <button class="btn-cancel">取消</button>
                    <button class="btn-save">保存</button>
                </div>
            </div>
        `;

        // 关闭按钮
        dialog.querySelector('.dialog-close').addEventListener('click', () => {
            dialog.remove();
        });
        dialog.querySelector('.btn-cancel').addEventListener('click', () => {
            dialog.remove();
        });

        // 保存按钮
        dialog.querySelector('.btn-save').addEventListener('click', () => {
            const name = document.getElementById('newAccountName').value.trim();
            const role = document.getElementById('newAccountRole').value.trim();
            const username = document.getElementById('newAccountUsername').value.trim();
            const password = document.getElementById('newAccountPassword').value;

            if (!name || !username) {
                alert('请填写姓名和用户名');
                return;
            }

            // 保存到localStorage
            const savedAccounts = localStorage.getItem('zentao_quick_accounts');
            let accounts = [];
            if (savedAccounts) {
                try {
                    accounts = JSON.parse(savedAccounts);
                } catch (e) {}
            }

            accounts.push({
                username,
                password,
                name,
                role: role || '用户',
                color: '#' + Math.floor(Math.random()*16777215).toString(16)
            });

            localStorage.setItem('zentao_quick_accounts', JSON.stringify(accounts));
            
            alert('账号已添加！刷新页面生效');
            dialog.remove();
        });

        document.body.appendChild(dialog);
    }

    /**
     * 添加登录页面样式
     */
    function addLoginPageStyles() {
        const style = document.createElement('style');
        style.textContent = `
            /* 快捷登录容器 */
            .quick-login-container {
                background: white;
                border-radius: 10px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                padding: 20px;
                min-width: 280px;
                max-width: 300px;
            }

            .quick-login-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                padding-bottom: 10px;
                border-bottom: 2px solid #f0f0f0;
            }

            .quick-login-header h3 {
                margin: 0;
                font-size: 16px;
                color: #333;
            }

            .add-account-btn {
                width: 28px;
                height: 28px;
                border-radius: 50%;
                border: 2px solid #667eea;
                background: white;
                color: #667eea;
                font-size: 20px;
                cursor: pointer;
                transition: all 0.2s;
            }

            .add-account-btn:hover {
                background: #667eea;
                color: white;
            }

            .quick-login-cards {
                display: flex;
                flex-direction: column;
                gap: 12px;
                max-height: 400px;
                overflow-y: auto;
            }

            .account-card {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 12px;
                border: 2px solid #e5e5e5;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.2s;
            }

            .account-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }

            .card-avatar {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-weight: 600;
                font-size: 18px;
            }

            .card-info {
                flex: 1;
            }

            .card-name {
                font-weight: 600;
                color: #333;
                font-size: 14px;
            }

            .card-role {
                font-size: 11px;
                color: #999;
            }

            .card-username {
                font-size: 11px;
                color: #666;
                font-family: monospace;
            }

            .card-login-btn {
                padding: 6px 16px;
                background: #667eea;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 12px;
                cursor: pointer;
                transition: background 0.2s;
            }

            .card-login-btn:hover {
                background: #5568d3;
            }

            .quick-login-footer {
                margin-top: 15px;
                text-align: center;
                font-size: 11px;
                color: #999;
            }

            /* 添加账号对话框 */
            .add-account-dialog {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                z-index: 99999;
            }

            .dialog-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
            }

            .dialog-content {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border-radius: 10px;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
                width: 400px;
                max-width: 90%;
            }

            .dialog-header {
                padding: 20px;
                border-bottom: 1px solid #eee;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .dialog-header h3 {
                margin: 0;
                font-size: 16px;
                color: #333;
            }

            .dialog-close {
                width: 30px;
                height: 30px;
                border: none;
                background: none;
                font-size: 24px;
                color: #999;
                cursor: pointer;
            }

            .dialog-close:hover {
                color: #333;
            }

            .dialog-body {
                padding: 20px;
            }

            .form-group {
                margin-bottom: 15px;
            }

            .form-group label {
                display: block;
                margin-bottom: 6px;
                font-size: 13px;
                color: #555;
                font-weight: 500;
            }

            .form-group input {
                width: 100%;
                padding: 8px 12px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 13px;
            }

            .form-group input:focus {
                outline: none;
                border-color: #667eea;
            }

            .form-group small {
                display: block;
                margin-top: 4px;
            }

            .dialog-footer {
                padding: 15px 20px;
                border-top: 1px solid #eee;
                display: flex;
                justify-content: flex-end;
                gap: 10px;
            }

            .dialog-footer button {
                padding: 8px 20px;
                border: none;
                border-radius: 4px;
                font-size: 13px;
                cursor: pointer;
            }

            .btn-cancel {
                background: #f5f5f5;
                color: #666;
            }

            .btn-cancel:hover {
                background: #e5e5e5;
            }

            .btn-save {
                background: #667eea;
                color: white;
            }

            .btn-save:hover {
                background: #5568d3;
            }
        `;
        document.head.appendChild(style);
    }

    /**
     * 初始化登录页面
     */
    function initLoginPage() {
        addLoginPageStyles();
        setTimeout(() => {
            createQuickLoginCards();
        }, 300);
        console.log('[禅道Bug提醒] 登录页面快捷登录已加载');
    }

    /**
     * 初始化Bug列表页面
     */
    function initBugListPage() {
        // 添加样式
        addCustomStyles();

        // 处理表格
        setTimeout(() => {
            processBugTable();
            createTodaySummary();
        }, 500);

        console.log('[禅道Bug提醒] Bug列表增强已加载');
    }

    /**
     * 主初始化
     */
    function init() {
        // 等待页面加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', init);
            return;
        }

        // 根据页面类型初始化不同功能
        const isLoginPage = window.location.href.includes('user-login');
        
        if (isLoginPage) {
            initLoginPage();
        } else {
            initBugListPage();
        }
    }

    // 启动
    init();
})();


